package com.fulin.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

/**
* 加密工具类
* @description RSA加密工具类
* @auther fulin16@crnet.com.hk
* @since 2020年1月13日 下午4:14:03
*
*/
public class RSAUtil {
	//指定加密算法是RSA
	private static String ALGORITHM = "RSA";
	//指定key的大小
	private static int KEYSIZE = 2084;
	
	private static String public_key = "";
	private static String private_key = "";
		
	/**
	 * 生成
	 * @throws Exception
	 */
	private static void generateKeyPair() throws Exception{
		//生成密钥对
		KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8")); // 说的一个安全的随机数
		kpg.initialize(KEYSIZE, secureRandom);
		KeyPair kp = kpg.generateKeyPair();
		//得到公钥和私钥
		Key publicKey = kp.getPublic();
		Key privateKey = kp.getPrivate();
		
		//将生产的密钥写入文件
		
		public_key = Base64.getEncoder().encodeToString(publicKey.getEncoded());
		private_key = Base64.getEncoder().encodeToString(privateKey.getEncoded());
		
		System.out.println("public_key => " + public_key);
		System.out.println("private_key => " + private_key);
	}
	
	private static String encrypt(String source) throws Exception{
		//获取公钥
		byte[] bytes = Base64.getDecoder().decode(public_key);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
		KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
		Key publicKey = keyFactory.generatePublic(x509KeySpec);
		
		//对数据加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] secu =  cipher.doFinal(source.getBytes());
		return new String(secu,"UTF-8");
	}
	
	private static String decrypr(String source) throws Exception{
		//获取私钥
		byte[] bytes = Base64.getDecoder().decode(private_key);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(bytes);
		KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		
		//对数据进行解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		
		byte[] local = cipher.doFinal(source.getBytes());
		return new String(local,"UTF-8");
	}
	
	public static void main(String[] args) throws Exception {
		RSAUtil.generateKeyPair();
		String source = "fulin's first test";
		String encrypt = RSAUtil.encrypt(source);
		System.out.println("密文 =>  " + encrypt);
		String decrypr = RSAUtil.decrypr(encrypt);
		System.out.println("明文 => " + decrypr);
	}
}
